import sys
import os

# 将项目根目录添加到模块搜索路径
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, project_root)

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from app.routers import auth
from app.core.database import Base, engine
from app.middlewares import uniform_restful_response, global_exception_handler, validate_request_params
from fastapi import HTTPException
from app.middlewares.exception_handler import (
    global_exception_handler,
    validation_exception_handler,
    http_exception_handler
)
from pydantic import ValidationError
from app.middlewares.token_verify import TokenVerificationMiddleware  # 新增导入

# 创建数据库表
Base.metadata.create_all(bind=engine)

app = FastAPI()

# 配置 CORS 中间件
origins = [
    "http://localhost",
    "http://localhost:8080",
    "http://127.0.0.1:8080",
    "http://127.0.0.1:8080"
    # 可以根据实际情况添加更多允许的源
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],  # 已允许所有头，包含Authorization
)


@app.get("/")
async def root():
    return {"message": "Weekly Report Analyzer Backend is running"}


# 注册中间件
# 注册中间件（注意顺序：建议在CORS之后，其他业务中间件之前）
app.add_middleware(TokenVerificationMiddleware)
app.middleware("http")(global_exception_handler)  # 启用全局异常处理
app.add_exception_handler(ValidationError, validation_exception_handler)  # 注册异常处理器
app.add_exception_handler(HTTPException, http_exception_handler)
app.middleware("http")(validate_request_params)
app.middleware("http")(uniform_restful_response)

# 注册路由
app.include_router(auth.router)

if __name__ == '__main__':
    import uvicorn

    # 修改 uvicorn 调用
    uvicorn.run(app, host="0.0.0.0", port=8000)
